import rpy
from rpy import r

from qgis.core import *
from qgis.gui import *

import catcher

def summary(obj):
    """ show a summary of an R object with name obj """
    c=catcher.Catcher()
    rpy.set_rpy_output(catcher.catcher)
    rpy.set_default_mode(rpy.NO_CONVERSION)
    summary=rpy.r("summary("+obj+")")
    rpy.set_default_mode(rpy.BASIC_CONVERSION)
    rpy.r.print_(summary)
    s = c.getText()
    c.reset()
    return s

def print_(obj):
    c=catcher.Catcher()
    rpy.set_rpy_output(catcher.catcher)
    rpy.set_default_mode(rpy.NO_CONVERSION)
    object=rpy.r.get(obj)
    rpy.set_default_mode(rpy.BASIC_CONVERSION)
    rpy.r.print_(object)
    s = c.getText()
    c.reset()
    return s
    
def getData(layer,name):
    data = []
    provider = layer.dataProvider()
    index = provider.fieldNameIndex(name)
    if layer.selectedFeatureCount() > 0:
        features = layer.selectedFeatures()
        [data.append(x.attributeMap()[index].toDouble()[0]) for x in features]
    else:
        for featureId in range(provider.featureCount()):
            feat = QgsFeature()
            provider.featureAtId(featureId,feat,True,[index])
            data.append(feat.attributeMap()[index].toDouble()[0])
    return data
        
def getXY(layer):
    x=[]
    y=[]
    if layer.selectedFeatureCount() > 0:
        fids = layer.selectedFeaturesIds()
    else:
        fids = range(layer.featureCount())
    for f in fids:
        feat=QgsFeature()
        layer.featureAtId(f,feat,True,0)
        p = feat.geometry().asPoint()
        x.append(p[0])
        y.append(p[1])
    return (x,y)


from qutils import showText

from PyQt4.QtCore import *
from PyQt4.QtGui import *

def show(s):
    window = QDialog()
    ui = showText.Ui_Dialog()
    ui.setupUi(window)
    ui.text.setText(s)
    window.show()
    window.exec_()
        
